var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pictrue_from:[],
    actionForm:'post'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    wx.getSystemInfo({
      success(res) {
        console.log(res)
        that.setData({
          windowWidth: res.windowWidth
        })
      }
    })
    if(e.id){
      that.setData({
        id:e.id
      })
      that.loadData();
    }
    if (e.show) {
      that.setData({
        show: e.show
      })
    }
    that.setData({
      server:app.server
    })
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    });
    util.getData("/atapi/delivery/process/orderDelivery", {
      'id': that.data.id||that.data.dlv_id
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.hideLoading();
        var odData = res.data.data;
        var pictrue_from = String(odData.pictrue_from).split(",");
        var pictrue_to = String(odData.pictrue_to).split(",");
        that.setData({
          id: odData.ID,
          name: odData.name,
          address: odData.address,
          pictrue_from: pictrue_from,
          pictrue_to: pictrue_to,
          goodsinfo: odData.goodsinfo || odData.loading_rule || odData.w_loading_rule,
          goodsinfo_from: odData.goodsinfo_from,
          goodsinfo_to: odData.goodsinfo_to,
          packages: odData.packages,
          package_from: odData.package_from,
          package_to: odData.package_to,
          box_number_out: odData.box_number_out,
          box_number_in: odData.box_number_in,
          delivery_rate: odData.delivery_rate,
          driver_rate: odData.driver_rate,
          remark: odData.remark_from,
          remark_to: odData.remark_to,
          goods_return: odData.goods_return,
          odData: odData,
          actionForm: 'put'
        })
        that.goodsDW();
        if (!that.data.show) {
          that.buildQRcode();
        }
      }
    });
  },
  buildQRcode:function(){
     var that = this;
    wx.showLoading({
      title: '生成二维码中...'
    });
     
    util.getData("/atapi/delivery/process/getQRcode", {
      'path': 'pages/driver/order_receiver?id=' + that.data.id,
      'width': that.data.windowWidth - 60,
      'id': that.data.id
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.hideLoading();
        //const base64 = wx.arrayBufferToBase64(res.data.data);
        console.log(res.data.data)
        that.setData({
          modalName: 'QRCode',
          qrurl: app.server+res.data.data
        });
      }
    });
  },
  formSubmit: function () {
    var that = this;
    wx.showLoading({
      title: '提交中...'
    });
    if (that.data.actionForm == 'post'){
      util.postData("/atapi/delivery/process/deliveryFromDriver", {
        'delivery': that.data.delivery,
        'shop': that.data.shop,
        'package_from': that.data.package_from,
        'goodsinfo_from': that.data.goodsinfo_from,
        'pictrue_from': that.data.pictrue_from.join(","),
        'remark_from': that.data.remark || '',
        'box_number_out': that.data.box_number_out||0,
        'user_id': app.globalData.user_id,
        'CO_ID': app.globalData.CO_ID,
        'name': that.data.name,
        'logs': '司机（' + app.globalData.truename + '）提交【' + that.data.name + '】的交接信息。货物数量：' + that.data.package + '，交付箱框：' + (that.data.box_number_out || 0) + '。备注：'+(that.data.remark || '无')
      }, function (res, error) {
        wx.hideLoading();
        console.log(res); console.log(error)
        if (res.data.success) {
          that.setData({
            id: res.data.id
          })
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.loadData();
                that.buildQRcode();
              }, 3000)
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    } else if (that.data.actionForm == 'put'){
      util.putData("/atapi/delivery/process/deliveryFromDriver", {
        'id': that.data.id,
        'delivery': that.data.delivery,
        'shop': that.data.shop,
        'package_from': that.data.package_from,
        'goodsinfo_from': that.data.goodsinfo_from,
        'pictrue_from': that.data.pictrue_from.join(","),
        'remark_from': that.data.remark || '',
        'user_id': app.globalData.user_id,
        'CO_ID': app.globalData.CO_ID,
        'name': that.data.name,
        'logs': '司机（' + app.globalData.truename + '）提交【' + that.data.name + '】的交接信息。货物数量：' + that.data.package + '，交付箱框：' + (that.data.box_number_out || 0) + '。'
      }, function (res, error) {
        wx.hideLoading();
        console.log(res); console.log(error)
        if (res.data.success) {
          that.setData({
            id: res.data.id
          })
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.loadData();
                that.buildQRcode();
              }, 3000)
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  bindGoodsInfoInput: function (e) {
    var that = this;
    var goods = that.data.goods;
    var packages = 0, goodsinfo = [];

    var value = e.detail.value;
    var id = e.currentTarget.id;

    for (var i = 0; i < goods.length; i++) {
      if (goods[i].id == id) {
        goods[i].number_from = value;
      }
      goodsinfo.push(goods[i].name + '|' + goods[i].ratio + '|' + goods[i].number_from)
      packages += (Number(goods[i].number_from) || 0) * (Number(goods[i].ratio)||0);
    }

    that.setData({
      goods: goods,
      package_from: packages,
      goodsinfo_from: goodsinfo.join(",")
    });

    return value;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'no_delivery_point',
      success: function (res) {
        if (res.data) {
          that.setData(res.data);
          that.goodsDW();
          if (res.data.dlv_id) {
            that.loadData();
          }
          wx.removeStorage({
            key: 'no_delivery_point',
            success: function (res) {
            }
          });
        }
      }
    }); 
  },
  goodsDW: function () {
    var that = this;
    var goods = [];
    var goodsinfo_from = that.data.goodsinfo_from||that.data.goodsinfo;
    var goodsinfo_to = that.data.goodsinfo_to;
    var goodsinfo = that.data.goodsinfo;
    var _goodsinfo = String(goodsinfo).split(",");
    var _goodsinfo_from = String(goodsinfo_from).split(",");
    var _goodsinfo_to = String(goodsinfo_to).split(",");
    if (goodsinfo) {
      if (goodsinfo_to) {
        for (var i = 0; i < _goodsinfo.length; i++) {
          var _item = String(_goodsinfo[i]).split("|");
          var _item_from = String(_goodsinfo_from[i]).split("|");
          var _item_to = String(_goodsinfo_to[i]).split("|");
          console.log(_item_from)
          goods.push({ "id": "LDR" + i, "name": _item[0], "ratio": _item[1], "number": _item[2], "number_from": _item_from[2], "number_to": _item_to[2] });
        }
      } else {
        for (var i = 0; i < _goodsinfo_from.length; i++) {
          var _item = String(_goodsinfo[i]).split("|");
          var _item_from = String(_goodsinfo_from[i]).split("|");
          console.log(_item_from)
          goods.push({ "id": "LDR" + i, "name": _item[0], "ratio": _item[1], "number": _item[2], "number_from": _item_from[2], "number_to": 0 });
        }
      }
    }
    that.setData({
      goods: goods
    })
  },
  chooseDeliveryImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var pictrue_from = that.data.pictrue_from;
    
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server + '/atapi/delivery/process/uploadDeliveryScene',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          success: function (res) {
            var data = JSON.parse(res.data); console.log(data)
            if (data.success) {
              pictrue_from.push(data.data);
              pictrue_from = util.arrayDeleteEmpty(pictrue_from);
              that.setData({
                pictrue_from: pictrue_from
              });
            } else {
              wx.showToast({
                title: "上传失败",
                image: '/images/wrong.png',
                duration: 2000
              });
            }
          },
          complete: function () {
            wx.hideLoading();
          }
        })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.pictrue_from;
    var url = imgList[index];
    wx.showLoading({
      title: '删除中...'
    });
    if (url == '') {
      if (imgList.length == 1) {
        imgList = [];
      } else {
        imgList.splice(index, 1);
      }
      if (type && type == 'tollfee') {
        that.setData({
          tollfeeImgList: imgList
        })
      }
      if (type && type == 'parkingfee') {
        that.setData({
          parkingfeeImgList: imgList
        })
      }
      if (type && type == 'delivery_picture') {
        that.setData({
          deliveryDocsImgList: imgList
        })
      }
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000,
        success: function () {

        }
      });
      return false;
    }
    util.putData("/atapi/delivery/process/deleteFile", {
      url: url
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        if (imgList.length == 1) {
          imgList = [];
        } else {
          imgList = util.arrayDeleteWithIndex(imgList, index, 1);
        }
        that.setData({
          pictrue_from: imgList
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {

          }
        });
      }
    });
  },
  previewImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var current = e.currentTarget.dataset.url
    var pictrue_from = that.data.pictrue_from;
    wx.previewImage({
      current: current,
      urls: pictrue_from
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})